#!/usr/bin/env bash

sccache_stop_server_and_show_stats() {
    sccache --stop-server || true && sccache --show-stats;
}

init_devcontainer() {
    # disable xtrace and history
    local xtrace_enabled=$(echo "${SHELLOPTS:-}" | grep -q 'xtrace'; echo $?);
    local history_enabled=$(echo "${SHELLOPTS:-}" | grep -q 'history'; echo $?);
    { set +xo history; } 2>/dev/null;
    eval "export $(find /run/secrets/ -type f -exec bash -c 'echo ${0/\/run\/secrets\//}=$(<${0})' {} \;)";
    if [ "${history_enabled}" -eq "0" ]; then { set -o history; } 2>/dev/null; fi;
    if [ "${xtrace_enabled}" -eq "0" ]; then { set -o xtrace; } 2>/dev/null; fi;

    set -xeo pipefail

    . devcontainer-utils-post-attach-command;

    sleep 10;
    . devcontainer-utils-vault-s3-test;
    . devcontainer-utils-vault-s3-export 0;
}

entrypoint() {
    set -x

    mkdir -p /home/coder/.cache;

    local secrets_dir=/run/secrets

    if [ -d "$secrets_dir" ] && [ "$(ls -A $secrets_dir)" ]; then
        init_devcontainer
    else
        sccache_stop_server_and_show_stats
    fi

    echo AWS_REGION=${AWS_REGION:-}
    echo AWS_SESSION_TOKEN=${AWS_SESSION_TOKEN:-}
    echo AWS_ACCESS_KEY_ID=${AWS_ACCESS_KEY_ID:-}
    echo AWS_SECRET_ACCESS_KEY=${AWS_SECRET_ACCESS_KEY:-}

    exec "$@";
}

entrypoint "$@";
